package net.fei.scan.quick.ui


import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.gson.Gson
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import net.fei.scan.quick.R
import net.fei.scan.quick.databinding.ActivityContentBinding
import net.fei.scan.quick.db.DbUtils
import net.fei.scan.quick.entity.History
import net.fei.scan.quick.util.BitMapUtil
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID


class ContentActivity : AppCompatActivity() {
    private lateinit var bin: ActivityContentBinding
    private lateinit var bitmap: Bitmap
    private var collectionStatus = true
    private var history1 = History()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bin = ActivityContentBinding.inflate(layoutInflater)
        setContentView(bin.root)
        initData()
        calculateWidth()
        favoriteEvents()
        bin.share.setOnClickListener {
            shareImage()
        }
    }

    private fun initData() {
        val datb = intent.getStringExtra("historys").toString()
        if (datb != null && datb.isNotEmpty() && !datb.equals("null")) {
            val history = Gson().fromJson(datb, History::class.java)
            history1.title = history.title
            history1.image = history.image
            history1.content = history.content
            bin.apply {
                img.setBackgroundResource(history.image)
                tetx.text = history.title
                val generateBitmap = generateBitmap(history.content, 200, 200)
                bitmap= generateBitmap!!
                Log.d("TAG", "$bitmap");
                bin.ma.setImageBitmap(generateBitmap)
            }
        }else{
            generateQRCode()
        }


    }

    private fun favoriteEvents() {
        bin.collection.setOnClickListener {
            if (collectionStatus) {
                insertData()
                bin.collection.setBackgroundResource(R.drawable.scs)
                collectionStatus = false
            } else {
                DbUtils(this).deleteData(1)
            }
        }

    }

    private fun insertData() {
        DbUtils(this@ContentActivity).insertData(
            history1.title, history1.content, "QR_CODE", history1.image, 0
        )
    }


    private fun calculateWidth() {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenWidth = displayMetrics.widthPixels
        val layoutWidth = (screenWidth * 0.9).toInt()
        val layoutParams = bin.layout.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.width = layoutWidth
        layoutParams.height = layoutWidth
        bin.layout.layoutParams = layoutParams
    }

    private fun generateQRCode() {
        val stringExtra = intent.getStringExtra("content")
        history1.content = stringExtra
        val generateBitmap = generateBitmap(stringExtra.toString(), 200, 200)
        bin.ma.setImageBitmap(generateBitmap)
        bitmap=generateBitmap!!
        Log.d("TAG", "$bitmap");
        bin.saveUser.setOnClickListener {
            val uri = BitMapUtil.saveBitmapToGallery(
                this@ContentActivity,
                generateBitmap!!,
                UUID.randomUUID().toString(),
                Environment.DIRECTORY_DCIM
            )
            Log.d("TAG", "$uri");
            if (uri != null) {
                Toast.makeText(this, getString(R.string.su), Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, getString(R.string.se), Toast.LENGTH_LONG).show()
            }
        }

        val data = intent.getStringExtra("data").toString()
        val history = Gson().fromJson(data, History::class.java)
        history1.title = history.title
        history1.image = history.image
        DbUtils(this).insertData(
            history.title, history1.content, "QR_CODE", history.image, 1
        )
        bin.apply {
            img.setBackgroundResource(history.image)
            tetx.text = history.title
        }

    }

    private fun generateBitmap(content: String, width: Int, height: Int): Bitmap? {
        val qrCodeWriter = QRCodeWriter()
        val hints: MutableMap<EncodeHintType, String?> = HashMap()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8"
        try {
            val encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints)
            val pixels = IntArray(width * height)
            for (i in 0 until height) {
                for (j in 0 until width) {
                    if (encode[j, i]) {
                        pixels[i * width + j] = 0x00000000
                    } else {
                        pixels[i * width + j] = -0x1
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565)
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }
    private fun shareImage() { // 获取ImageView中的Bitmap
        val drawable = bin.ma.drawable as BitmapDrawable
        val bitmap = drawable.bitmap
        val path =
            MediaStore.Images.Media.insertImage(contentResolver, bitmap, "Image Description", null)
        val imageUri = Uri.parse(path)
        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.type = "image/*"
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
        startActivity(Intent.createChooser(shareIntent, getString(R.string.lsja)))
    }


}